<?php
/**
 * Created by PhpStorm.
 * User: Argon
 * Date: 2016/12/15
 * Time: 14:45
 */

namespace Admin\Model;
use Admin\Logic\MySQLORM;
use Admin\Logic\NestedSets;
use Think\Model;

class PermissionModel extends Model
{
    protected $_validate=[
        ['parent_id','require','请选择父级权限'],
        ['name','require','请输入权限名称'],
    ];

    public function getList() {
        return $this->order('lft')->select();
    }

    public function addPermission(){
        $orm=new MySQLORM();
        $NestedSets=new NestedSets($orm, $this->getTableName(), 'lft', 'rght', 'parent_id', 'id', 'level');
        if ($NestedSets->insert($this->data['parent_id'], $this->data, 'bottom')===false) {
            $this->error="添加权限失败";
            return false;
        }
        return true;
    }

    public function savePermission() {
        $parent_id  = $this->where(['id' => $this->data['id']])->getField('parent_id');
        if($parent_id != $this->data['parent_id']){
            $orm        = new MysqlORM();
            $nestedsets = new NestedSets($orm, $this->getTableName(), 'lft', 'rght', 'parent_id', 'id', 'level');
            if ($nestedsets->moveUnder($this->data['id'], $this->data['parent_id'], 'bottom') === false) {
                $this->error = '不能将分类移动到自身或后代分类中';
                return false;
            }
        }
        return $this->save();
    }

    public function deletePermission($id){
        $orm=new MysqlORM();
        $NestedSets=new NestedSets($orm, $this->getTableName(), 'lft', 'rght', 'parent_id', 'id', 'level');
        if ($NestedSets->delete($id) === false) {
            $this->error = '删除失败';
            return false;
        }
        return true;
    }
}